import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 调用时先从本地获取car的值转换成数组，再放到store中
// eslint-disable-next-line no-unused-expressions
var car = JSON.parse(localStorage.getItem('car') || '[]')
export default new Vuex.Store({
  state: { // this.$store.state.count
    // 将商品的数据存储起来{商品ID，count,价格}
    car: car
  },
  mutations: { // this.$store.commit('方法名',参数)
    addToCar (state, goodsinfo) {
      // eslint-disable-next-line no-unused-vars
      var flag = false
      state.car.some(item => {
        // eslint-disable-next-line eqeqeq
        if (item.id == goodsinfo.id) {
          item.count += parseInt(goodsinfo.count)
          flag = true
          return true
        }
      })
      if (!flag) {
        state.car.push(goodsinfo)
      }
      // d当更新时存储到本地的localStorage中
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    updateGoodsInfo (state, goodsinfo) {
      // 修改商品中的购物数量值
      state.car.some(item => {
        // eslint-disable-next-line eqeqeq
        if (item.id == goodsinfo.id) {
          item.count = parseInt(goodsinfo.count)
          return true
        }
      })
      // 当修改完商品的数量，把最新的数据保存到本地存储
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    removeFormCar (state, id) {
      // 根据id，从store购物车中对应商品数据删除
      state.car.some((item, i) => {
        // eslint-disable-next-line eqeqeq
        if (item.id == id) {
          state.car.splice(i, 1)
          return true
        }
      })
      // 将删除完毕的购物车数据存到本地
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    updataGoodsSelected (state, info) {
      state.car.some(item => {
        // eslint-disable-next-line eqeqeq
        if (item.id == info.id) {
          item.selected = info.selected
        }
        return true
      })
      // 把最新的购物车所有状态保存到本地里面去
      localStorage.setItem('car', JSON.stringify(state.car))
    }
  },
  getters: { // this.$store.getters.***
    getAllCount (state) {
      var c = 0
      state.car.forEach(item => {
        c += item.count
      })
      return c
    },
    getGoodsCount (state) {
      var o = {}
      state.car.forEach(item => {
        o[item.id] = item.count
      })
      return o
    },
    getGoodsSelected (state) {
      var o = {}
      state.car.forEach(item => {
        o[item.id] = item.selected
      })
      return o
    },
    getGoodsCountAndAmount (state) {
      var o = {
        count: 0, // 勾选的数量
        amount: 0 // 勾选的总价
      }
      state.car.forEach(item => {
        if (item.selected) {
          o.count += item.count
          o.amount += item.price * item.count
        }
      })
      return o
    }
  }
})
